package com.yupi.kqapibackend.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.kqapiclientsdk.client.kqApiClient;
import com.google.gson.Gson;
import com.yupi.kqapibackend.annotation.AuthCheck;
import com.yupi.kqapibackend.common.BaseResponse;
import com.yupi.kqapibackend.common.DeleteRequest;
import com.yupi.kqapibackend.common.ErrorCode;
import com.yupi.kqapibackend.common.ResultUtils;
import com.yupi.kqapibackend.constant.UserConstant;
import com.yupi.kqapibackend.exception.BusinessException;
import com.yupi.kqapibackend.exception.ThrowUtils;
import com.yupi.kqapibackend.model.dto.InterfaceInfoInvokeRequest;
import com.yupi.kqapibackend.model.dto.InterfaceInfoOnlineRequest;
import com.yupi.kqapibackend.model.dto.interfaceinfo.InterfaceInfoAddRequest;
import com.yupi.kqapibackend.model.dto.interfaceinfo.InterfaceInfoEditRequest;
import com.yupi.kqapibackend.model.dto.interfaceinfo.InterfaceInfoUpdateRequest;
import com.yupi.kqapibackend.model.entity.InterfaceInfo;
import com.yupi.kqapibackend.model.entity.User;
import com.yupi.kqapibackend.service.InterfaceInfoService;
import com.yupi.kqapibackend.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 帖子接口
 *
 * @author <a href="https://github.com/liyupi">程序员鱼皮</a>
 * @from <a href="https://yupi.icu">编程导航知识星球</a>
 */
@RestController
@RequestMapping("/interfaceInfo")
@Slf4j
public class InterfaceInfoController {

    @Resource
    private InterfaceInfoService interfaceinfoService;

    @Resource
    private UserService userService;

    private final static Gson gson = new Gson();


    // region 增删改查

    /**
     * 创建
     */
    @PostMapping("/add")
    public BaseResponse<Long> addInterfaceInfo(@RequestBody InterfaceInfoAddRequest interfaceinfoAddRequest, HttpServletRequest request) {
        // 1. 传入参数的校验
        if (interfaceinfoAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        InterfaceInfo interfaceinfo = new InterfaceInfo();
        BeanUtils.copyProperties(interfaceinfoAddRequest, interfaceinfo);
        User loginUser = userService.getLoginUser(request);
        interfaceinfo.setUserId(loginUser.getId());
        boolean result = interfaceinfoService.save(interfaceinfo);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        long newInterfaceInfoId = interfaceinfo.getId();
        return ResultUtils.success(newInterfaceInfoId);
    }

    /**
     * 删除
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteInterfaceInfo(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        InterfaceInfo oldInterfaceInfo = interfaceinfoService.getById(id);
        ThrowUtils.throwIf(oldInterfaceInfo == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldInterfaceInfo.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = interfaceinfoService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新（仅管理员）
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateInterfaceInfo(@RequestBody InterfaceInfoUpdateRequest interfaceinfoUpdateRequest) {
        if (interfaceinfoUpdateRequest == null || interfaceinfoUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        InterfaceInfo interfaceinfo = new InterfaceInfo();
        BeanUtils.copyProperties(interfaceinfoUpdateRequest, interfaceinfo);
        // 参数校验
        interfaceinfoService.validInterfaceInfo(interfaceinfo, false);
        long id = interfaceinfoUpdateRequest.getId();
        // 判断是否存在
        InterfaceInfo oldInterfaceInfo = interfaceinfoService.getById(id);
        ThrowUtils.throwIf(oldInterfaceInfo == null, ErrorCode.NOT_FOUND_ERROR);
        boolean result = interfaceinfoService.updateById(interfaceinfo);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取
     */
    @GetMapping("/get")
    public BaseResponse<InterfaceInfo> getInterfaceInfoVOById(long id) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        InterfaceInfo interfaceinfo = interfaceinfoService.getById(id);
        if (interfaceinfo == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        QueryWrapper<InterfaceInfo> interfaceInfoQueryWrapper = new QueryWrapper<>();
        interfaceInfoQueryWrapper.eq("id", id);
        return ResultUtils.success(interfaceinfoService.getOne(interfaceInfoQueryWrapper));
    }

    @PostMapping("/invoke")
    public BaseResponse<Object> invokeInterface(@RequestBody InterfaceInfoInvokeRequest interfaceInfoInvokeRequest,
                                                HttpServletRequest request) {
        String requestParams = interfaceInfoInvokeRequest.getUserRequestParams();
        User loginUser = userService.getLoginUser(request);
        String accessKey = loginUser.getAccessKey();
        com.example.kqapiclientsdk.client.kqApiClient kqApiClient = new kqApiClient(accessKey);
        com.example.kqapiclientsdk.model.entity.User user = gson.fromJson(requestParams, com.example.kqapiclientsdk.model.entity.User.class);
        String name = user.getName();
        return ResultUtils.success(kqApiClient.nameByGet(name));
    }

    /**
     * 接口上线操作
     */
    @PostMapping("/online")
    public BaseResponse<Boolean> onlineInterface(@RequestBody InterfaceInfoOnlineRequest onlineRequest, HttpServletRequest request) {
        // 1.鉴权
        if (!userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        Long UId = interfaceinfoService.onlineInterface(onlineRequest.getId());
        return ResultUtils.success(true);
    }

    /**
     * 接口下线操作
     */
    @PostMapping("/offline")
    public BaseResponse<Boolean> offlineInterface(@RequestBody InterfaceInfoOnlineRequest onlineRequest, HttpServletRequest request) {
        // 1.鉴权
        if (!userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        Long UId = interfaceinfoService.offlineInterface(onlineRequest.getId());
        return ResultUtils.success(true);
    }
    /**
     * 分页获取列表（封装类）
     */
    @GetMapping("/list/page")
    public BaseResponse<Page<InterfaceInfo>> listInterfaceInfoVOByPage(Integer current, Integer pageSize ) {

        // 限制爬虫
        ThrowUtils.throwIf(pageSize > 20, ErrorCode.PARAMS_ERROR);
        Page<InterfaceInfo> page = new Page<>(current, pageSize);
        return ResultUtils.success(interfaceinfoService.page(page));
    }



    /**
     * 编辑（用户）
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editInterfaceInfo(@RequestBody InterfaceInfoEditRequest interfaceinfoEditRequest, HttpServletRequest request) {
        if (interfaceinfoEditRequest == null || interfaceinfoEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        InterfaceInfo interfaceinfo = new InterfaceInfo();
        // 参数校验
        interfaceinfoService.validInterfaceInfo(interfaceinfo, false);
        User loginUser = userService.getLoginUser(request);
        long id = interfaceinfoEditRequest.getId();
        // 判断是否存在
        InterfaceInfo oldInterfaceInfo = interfaceinfoService.getById(id);
        ThrowUtils.throwIf(oldInterfaceInfo == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldInterfaceInfo.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean result = interfaceinfoService.updateById(interfaceinfo);
        return ResultUtils.success(result);
    }

}
